<?php
require_once 'Article.php';
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BDDArticle
 *
 * @author Gael
 */
class BDDArticle extends Article {
    function __construct($id, $codebare, $typearticle) {
        parent::__construct($id,$codebare,$typearticle);
    }
            static public function byId($id){
        try{
            $db= getPdo();
            try{ // on essai de lancer une transaction au cas ou elle serait déjà lancer dans une autre fonction
                $db->beginTransaction();
                $commit = true;
            }catch(PDOException $e){
                $commit = false;
                //echo'capture de lancement de transaction :'. $e->getMessage();
            }
            $rep = $db->query("select * from article where id=$id" );
            
            while($data =$rep->fetch()){
                $ta= new BDDArticle($data['id'], $data['codebarre'], BDDTypeArticle::byId($data['idtypearticle']));
            }
            if($commit){ $db->commit();}
            $rep->closeCursor();
            return $ta;
            
        }catch(Exception $e){
            $db->rollBack();
            print('erreur requete'.$e->getMessage());
            return false;
        }
    }
    static public function all(){
        try{
            $db= getPdo();
            $tab = array();
            
            $rep = $db->query("select * from article  " );
            while($data =$rep->fetch()){
                $tab[$data['id']    ]=new BDDArticle($data['id'], $data['codebarre'], BDDTypeArticle::byId($data['idtypearticle']));
                
            }
            $rep->closeCursor();
            return $tab;
        }catch(Exception $e){
            die('erreur requete'.$e->getMessage());
        }
    } 

   static function insArticle($typearticle){
       try{
           // clé unique permettant de récupérer l'id autoincrémenté de l'enregistrement
           $unique = uniqid('maco');
           $db= getPdo();
           $req = $db->prepare("INSERT INTO article(id, codebarre, idtypearticle) VALUES(:id, :unique, :idtypearticle)");
           if($req->execute(array('id' => NULL,'unique' => $unique,'idtypearticle' => $typearticle))){
               

               return $unique;
           }else{
               return null;
           }
           
           
        }catch(Exception $e){
            die($e->getMessage());
        }
       
    
   }
   function updateCodebarre($codebarre){
       try{
            $db= getPdo();
            $db->exec("UPDATE article SET codebarre = $codebarre WHERE id=$this->id");
            
       }catch(Exception $e){
            die($e->getMessage());
        }
   }
}

?>
